#include <stdio.h>
#include "localsearcher.h"
#include "EasyBMP.h"
#include<Windows.h>
#include "priorityqueueimpl.h"

bool isStart(RGBApixel pixel){
	return pixel.Blue==0 && pixel.Green==0 && pixel.Red==255;
}

bool isEnd(RGBApixel pixel){
	return pixel.Blue==255 && pixel.Green==0 && pixel.Red==0;
}

bool isWalkable(RGBApixel pixel){
	return pixel.Blue==255 && pixel.Green==255 && pixel.Red==255;
}


class IntegerQueueComparator:public QueueComparator{
public:
	virtual int compareTo(void*lhs, void*rhs){
		int x=*(int*)lhs;
		int y=*(int*)rhs;
		return (x < y) ? -1 : ((x == y) ? 0 : 1);
	}
};



int main() {
	try{
	/*int**tarray=new int*[10];
	int intArray[]={5,98,0,84,42,32,11,91,101,2};
	
	for(int i=0;i<10;i++){
		int*value=new int;
		*value=intArray[i];
		tarray[i]=value;
	}
	PriorityQueue<int>q(new IntegerQueueComparator());
	int newLength=7;
	int**tarray2=q.copyOfArray(tarray,10,newLength);
	
	for(int i=0;i<newLength;i++){
		int value=tarray2[i]==NULL?0: *(tarray2[i]);
		printf("%d\n", value);
	}*/
	

	
	/*int intArray[]={5,98,0,84,42,32,11,91,101,2};

	PriorityQueue<int>q(2,new IntegerQueueComparator());

	for(int i=0;i<10;i++){
		int*value=new int;
		*value=intArray[i];
		q.offer(value);
	}
        
	while(q.getSize()>0){
		int value=*(q.poll());
		printf("%d\n",value);
    }*/
	BMP bmp;
	bmp.ReadFromFile("map.bmp");
	int width=bmp.TellWidth();
	int height=bmp.TellHeight();
	bool**grid=new bool*[height];
	Point start(-1,-1);
	Point end(-1,-1);
	for(int j=0;j<height;j++){
		grid[j]=new bool[width];
		for(int i=0;i<width;i++){
			RGBApixel pixel=bmp.GetPixel(i,j);
			bool walkable=true;
			if(isStart(pixel)){
				start.setX(i);start.setY(j);
			}else if(isEnd(pixel)){
				end.setX(i);end.setY(j);
			}else if(!isWalkable(pixel)){
				walkable=false;
			}

			grid[j][i]=walkable;
		}
	}
	
	if(start.getX()==-1 && start.getY()==-1){
		printf("start Red pixel is not defined on the map");
		return 0;
	}

	if(end.getX()==-1 && end.getY()==-1){
		printf("end Blue pixel is not defined on the map");
		return 0;
	}

	GridSearch search(grid,width,height,&end);
	long l=GetTickCount();
	std::vector<Point*>result=search.compute(&start);
	long l2=GetTickCount();
	printf("result = %d. time=%d",result.size(), l2-l);
	RGBApixel p;
	p.Red=255;
	p.Green=255;
	p.Blue=0;
	for(unsigned int i=0;i<result.size();i++){
		Point*pi=result[i];
		bmp.SetPixel(pi->getX(), pi->getY(), p);
		//delete pi;
		result[i]=NULL;
	}
	//result.clear();
	//result.shrink_to_fit();

	printf("pccount=%d",search.getPcCount());
	bmp.WriteToFile("mapcpp.bmp");
	}catch(char*t){
		printf("Exception ex=%s\n",t);
	}
	return 0;
}
